package gui.android;

import perv_comp.abbs.cok.R;
import database.dbUserImpl;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class UserAuthentication extends Activity implements OnClickListener {

	private EditText email;
	private EditText password;
	SQLiteDatabase mydb;
	private  String DBNAME = "PERSONS.db";   
	private  String TABLE = "MY_TABLE"; 
	private Button login;
	boolean passValid = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
		setContentView(R.layout.password_dialog);
		email = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		login = (Button) findViewById(R.id.login);
		login.setOnClickListener(this);
	}

	@Override	
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.user_authentication, menu);
		return true;
	}

	@Override
	public void onClick(View component) {
		createDB();
		final String name = email.getText().toString();
		final String pword = password.getText().toString();
//		readFromDB();
		dbUserImpl dbU = new dbUserImpl();
		passValid = dbU.checkUserPwd(name, pword);
		if (passValid) {
			Intent intent = new Intent(this, Play_Exit_Menu.class);
			startActivity(intent);
		}
	}

	
	private void createDB() {
		dbUserImpl dbU = new dbUserImpl();
		int id = Integer.parseInt(dbU.getPID(email.getText().toString()));
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		mydb.execSQL("DROP TABLE IF EXISTS " + TABLE );
		mydb.execSQL("CREATE TABLE IF  NOT EXISTS "+ TABLE +" (ID INTEGER PRIMARY KEY, NAME TEXT, CHOICE INTEGER, ROLLE INTEGER, OPPONENTID INT, OPPONENTANIMAL INT, GAMEID INT);");
		mydb.execSQL("INSERT INTO " + TABLE	+ "(ID, NAME, CHOICE,ROLLE,OPPONENTID, OPPONENTANIMAL, GAMEID) VALUES("+id+",'"+email.getText().toString()+"',0,0,0,0,0)");
		mydb.close();
	}
}
